/*
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.teremail.panto;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PushbackInputStream;

/**
 * @author Michael Barker <mailto:mike@middlesoft.co.uk>
 * @version $Revision: 1.2 $
 */
public class IOUtil {

    /**
     * Takes a byte array that was previously an object and converts it back.
     * 
     * @param data
     * @return
     */
    public static Object byteArrayToObject(byte[] data) {
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(data);
            ObjectInputStream oin = new ObjectInputStream(bais);
            return oin.readObject();
        } catch (IOException e) {
            throw new RuntimeException("Error restoring object", e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Error restoring object", e);
        }
    }

    /**
     * Converts an object to a byte array.
     * 
     * @param o
     * @return
     */
    public static byte[] objectToByteArray(Object o) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(baos);
            out.writeObject(o);

            return baos.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("Error serializing object", e);
        }
    }

    /**
     * Closes an input stream and catches any errors in close.
     * 
     * @param in
     */
    public static void quietClose(InputStream in) {
        if (in != null) {
            try {
                in.close();
            } catch (Throwable t) {
            }
        }
    }

    /**
     * Closes an output stream without throwing an exception
     * 
     * @param log
     * @param out
     */
    public static void quietClose(OutputStream out) {
        if (out != null) {
            try {
                out.close();
            } catch (Throwable t) {
            }
        }
    }

    /**
     * Appends a line from the input stream to the supplied stringbuilder.
     * Supports line termination with '\r', '\n', '\n\r', '\r\n'.
     * 
     * @param b
     *            The StringBuilder to append the result to.
     * @param in
     *            The input stream to read from (must support mark(int)).
     * @param charSet
     *            The charset to encode to.
     * @return The number of bytes read including the terminator.
     * @throws IOException
     */
    public static int appendLine(StringBuilder b, InputStream in, String charSet)
            throws IOException {

        int numRead = 0;

        if (!in.markSupported()) {
            throw new IOException("mark(int) not support for input stream");
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream(128);

        int c;
        while ((c = in.read()) != -1) {
            numRead++;
            if (c == '\r' || c == '\n') {
                char expected = (c == '\r') ? '\n' : '\r';
                in.mark(1);
                int nextC = in.read();
                if (nextC == expected) {
                    numRead++;
                } else {
                    in.reset();
                }
                break;
            } else {
                out.write(c);
            }
        }

        if (out.size() > 0) {
            b.append(out.toString(charSet));
        }

        return numRead;
    }

    public static int appendLine(StringBuilder b, PushbackInputStream in,
            String charSet) throws IOException {

        int numRead = 0;

        ByteArrayOutputStream out = new ByteArrayOutputStream(128);

        int c;
        while ((c = in.read()) != -1) {
            numRead++;
            if (c == '\r' || c == '\n') {
                char expected = (c == '\r') ? '\n' : '\r';
                int nextC = in.read();
                if (nextC == expected) {
                    numRead++;
                } else {
                    in.unread(nextC);
                }
                break;
            } else {
                out.write(c);
            }
        }

        if (out.size() > 0) {
            b.append(out.toString(charSet));
        }

        return numRead;
    }

    public static String toString(InputStream in, String encoding)
            throws IOException {
        byte[] b = new byte[8192];
        StringBuilder sb = new StringBuilder();
        for (int numRead = 0; (numRead = in.read(b)) != -1;) {
            sb.append(new String(b, 0, numRead, encoding));
        }
        return sb.toString();
    }
    
    
    public static long count(InputStream in) throws IOException {
        long total = 0;
        byte[] b = new byte[8192];
        int i = 0;
        while ((i = in.read(b)) != -1) {
            total += i;
        }
        return total;
    }
    
    public static void dump(String filename, InputStream in) throws IOException {
        FileOutputStream fout = new FileOutputStream(filename);
        copy(in, fout);
        fout.flush();
        fout.close();
    }

    public static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] b = new byte[8192];
        for (int numRead = 0; (numRead = in.read(b)) != -1;) {
            out.write(b, 0, numRead);
        }
    }
}
